# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from .models import BlogMsg, BlogType
from .serializer import BlogMsgSerializer, BlogTypeSerializer
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework import filters
from rest_framework import pagination
from rest_framework.response import Response
from django_filters import rest_framework

# Create your views here.


class BlogMsgPagination(pagination.PageNumberPagination):
    """
    博客分页配置类
    """
    page_size = 5
    page_size_query_param = 'page_size'
    page_query_param = 'page'
    max_page_size = 10


class BlogMsgViewSet(viewsets.GenericViewSet,
                     mixins.ListModelMixin,
                     mixins.RetrieveModelMixin):
    """
    博客展示ViewSet
    """
    queryset = BlogMsg.objects.filter(is_public=0).order_by('update_time')
    serializer_class = BlogMsgSerializer
    filter_backends = (rest_framework.DjangoFilterBackend, filters.OrderingFilter)
    pagination_class = BlogMsgPagination
    filter_fields = ('blog_type', 'blog_tags', )
    ordering_fields = ('update_time', )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.views += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class BLogTypeViewSet(viewsets.GenericViewSet,
                      mixins.ListModelMixin):
    """
    博客类型展示ViewSet
    """
    queryset = BlogType.objects.all()
    serializer_class = BlogTypeSerializer
